﻿using System;
using System.Reflection;
using System.Configuration;
using FrankJie.Cache;
namespace FrankJie.IDAL
{
	/// <summary>
	/// 抽象工厂模式创建DAL。
	/// web.config 需要加入配置：(利用工厂模式+反射机制+缓存机制,实现动态创建不同的数据层对象接口) 
	/// DataCache类在导出代码的文件夹里
	/// <appSettings> 
	/// <add key="DAL" value="FrankJie.SQLServerDAL" /> (这里的命名空间根据实际情况更改为自己项目的命名空间)
	/// </appSettings> 
	/// </summary>
	public sealed class DataAccess//<t>
	{
		private static readonly string AssemblyPath = ConfigurationManager.AppSettings["DAL"];
		/// <summary>
		/// 创建对象或从缓存获取
		/// </summary>
		public static object CreateObject(string AssemblyPath,string ClassNamespace)
		{
            object objType = CacheStrategy.GetObject(ClassNamespace);//从缓存读取
			if (objType == null)
			{
				try
				{
					objType = Assembly.Load(AssemblyPath).CreateInstance(ClassNamespace);//反射创建
					CacheStrategy.AddObject(ClassNamespace, objType);// 写入缓存
				}
				catch
				{}
			}
			return objType;
		}

		/// <summary>
		/// 创建数据层接口
		/// </summary>
		//public static t Create(string ClassName)
		//{
			//string ClassNamespace = AssemblyPath +"."+ ClassName;
			//object objType = CreateObject(AssemblyPath, ClassNamespace);
			//return (t)objType;
		//}

		/// <summary>
		/// 创建分类数据层接口。
		/// </summary>
		public static ICategory CreateCategory()
		{

			string ClassNamespace = AssemblyPath +".Category";
			object objType=CreateObject(AssemblyPath,ClassNamespace);
			return (ICategory)objType;
		}


		/// <summary>
		/// 创建评论数据层接口。
		/// </summary>
		public static FrankJie.IDAL.IComment CreateComment()
		{

			string ClassNamespace = AssemblyPath +".Comment";
			object objType=CreateObject(AssemblyPath,ClassNamespace);
			return (FrankJie.IDAL.IComment)objType;
		}


		/// <summary>
		/// 创建友情链接数据层接口。
		/// </summary>
		public static FrankJie.IDAL.ILink CreateLink()
		{

			string ClassNamespace = AssemblyPath +".Link";
			object objType=CreateObject(AssemblyPath,ClassNamespace);
			return (FrankJie.IDAL.ILink)objType;
		}


		/// <summary>
		/// 创建管理员数据层接口。
		/// </summary>
		public static FrankJie.IDAL.IManager CreateManager()
		{

			string ClassNamespace = AssemblyPath +".Manager";
			object objType=CreateObject(AssemblyPath,ClassNamespace);
			return (FrankJie.IDAL.IManager)objType;
		}

		/// <summary>
		/// 创建文章数据层接口。
		/// </summary>
		public static FrankJie.IDAL.IPost CreatePost()
		{

			string ClassNamespace = AssemblyPath +".Post";
			object objType=CreateObject(AssemblyPath,ClassNamespace);
			return (FrankJie.IDAL.IPost)objType;
		}


		/// <summary>
		/// 创建标签数据层接口。
		/// </summary>
		public static FrankJie.IDAL.ITag CreateTag()
		{

			string ClassNamespace = AssemblyPath +".Tag";
			object objType=CreateObject(AssemblyPath,ClassNamespace);
			return (FrankJie.IDAL.ITag)objType;
		}

}
}